package com.xlh.dokka.svc.core.novnc;

import com.xlh.dokka.svc.properties.NovncProperties;
import com.xlh.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * novnc服务器与应用服务器在一台物理机上时，使用本地IO写文件
 *
 * @author cheer
 */
@Slf4j
public class LocalNovncConnector extends AbstractNovncConnector implements NovncConnector {

    private final String tokenDir;

    public LocalNovncConnector() {
        NovncProperties novncProperties = SpringContextUtil.getBean(NovncProperties.class);
        this.tokenDir = novncProperties.getDir() + "/utils/websockify/token/";
        this.prefix = novncProperties.getPrefix();
    }

    @Override
    protected Boolean writeToken(Long dokkaId, String vnc) {
        String tokenKey = prefix + dokkaId;
        try {
            FileUtils.writeStringToFile(new File(tokenDir + tokenKey), tokenKey + ": " + vnc);
            return true;
        } catch (IOException e) {
            log.error("novnc write token {} failed", tokenKey, e);
        }
        return false;
    }

    @Override
    public void initialize() {

    }

    @Override
    public void deleteToken(Long dokkaId) {
        String tokenKey = prefix + dokkaId;
        try {
            FileUtils.forceDelete(new File(tokenDir + tokenKey));
        } catch (FileNotFoundException ignored) {
        } catch (IOException e) {
            log.error("novnc delete {} token failed", tokenKey, e);
        }
    }
}
